package threadpoolnio.threadpool;

import java.util.concurrent.*;

/**
 * @author ：xx
 * @date ：Created in 2020/3/17 19:43
 * @description：
 * @modified By：
 */
public class PoolHelper {
    private static ExecutorService threadPool=null;
    private static int poolSize=1;
    public  static ExecutorService getPool() {
        if(threadPool==null) {
            int cpuNums = Runtime.getRuntime().availableProcessors();
            poolSize = 2 * cpuNums;
            threadPool = new ThreadPoolExecutor(poolSize, poolSize, 5, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(1),
                    new NamedThreadFactory("线程"),
                    new RejectedExecutionHandler() {
                        @Override
                        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                            System.out.println("当然任务被拒绝了：" + r.toString());
                        }
                    }) {
                @Override
                protected void beforeExecute(Thread t, Runnable r) {
                    super.beforeExecute(t, r);
//                System.out.println("当前的任务数"+this.getTaskCount()+"已完成的任务数："+this.getCompletedTaskCount()+"等待执行……"+r.toString());
                }

                @Override
                protected void afterExecute(Runnable r, Throwable t) {
                    super.afterExecute(r, t);
//                System.out.println("执行完毕……"+r.toString());
                }

                @Override
                protected void terminated() {
                    super.terminated();
                    System.out.println("线程池结束");
                }
            };
        }
        return threadPool;
    }
}
